package modules.warn.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.common.service.SmsService;
import luxing.constant.SmsConfig;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.DateUtil;
import luxing.util.JsonUtil;
import luxing.util.LoginUserUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import manage.tenant.entity.Tenant;
import manage.tenant.service.TenantService;
import modules.arc.entity.Vehicle;
import modules.arc.entity.VehicleWarn;
import modules.arc.service.VehicleWarnService;
import modules.sys.entity.Log;
import modules.sys.service.LogService;
import modules.warn.entity.VehicleWarnHis;
import modules.warn.entity.WarnType;
import modules.warn.service.WarnTypeService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/vehicleWarnController")
public class VehicleWarnController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(VehicleWarnController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private VehicleWarnService vehicleWarnService;
	@Autowired
	private WarnTypeService warnTypeService;
	@Autowired
	private TenantService tenantService;
	@Autowired
	private SmsService smsService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		List<WarnType> warnTypeList = warnTypeService.listByStatus(WarnType.STATUS_ENABLE);
		request.setAttribute("warnTypeList", warnTypeList);
		return new ModelAndView("modules/warn/vehicleWarn-list");
	}

	/**
	 * 办理记录列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "hisIndex")
	public ModelAndView hisIndex(HttpServletRequest request) {
		return new ModelAndView("modules/warn/vehicleWarnHis-list");
	}

	/**
	 * 列表数据
	 * 
	 * @param vehicleWarn
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(VehicleWarn vehicleWarn, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(VehicleWarn.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicleWarn, request.getParameterMap());
			// 提醒状态
			String status = request.getParameter("ws");
			status = StringUtils.isBlank(status) ? VehicleWarn.STATUS_NORMAL : status;
			if (!status.equals(VehicleWarn.STATUS_ALL)) {
				cq.eq("status", status);
			}
			// 提醒类型
			String warnType = request.getParameter("wt");
			if (StringUtils.isNotBlank(warnType)) {
				cq.eq("warnType.id", warnType);
			}
			// 下月到期||时间范围
			String warnDateType = request.getParameter("warnDateType");
			String warnDateBegin = request.getParameter("warnDate_begin");
			String warnDateEnd = request.getParameter("warnDate_end");
			if (StringUtils.isNotBlank(warnDateBegin) || StringUtils.isNotBlank(warnDateEnd)
					|| (warnDateType != null && warnDateType.equals("2"))) {
				// 按时间范围
				if (StringUtils.isNotBlank(warnDateBegin)) {
					cq.ge("warnDate", DateUtil.strToDate(warnDateBegin, "yyyy-MM-dd"));
				}
				if (StringUtils.isNotBlank(warnDateEnd)) {
					cq.le("warnDate", DateUtil.strToDate(warnDateEnd, "yyyy-MM-dd"));
				}
			} else if ((warnDateType == null || warnDateType.equals("1"))
					&& (StringUtils.isBlank(warnDateBegin) && StringUtils.isBlank(warnDateEnd))) {
				// 下月到期
				Calendar calBegin = Calendar.getInstance();
				calBegin.add(Calendar.YEAR, -100);
				cq.ge("warnDate", calBegin.getTime());
				Calendar calEnd = Calendar.getInstance();
				calEnd.add(Calendar.MONTH, 2);
				calEnd.set(Calendar.DATE, 0);
				cq.le("warnDate", calEnd.getTime());
			}
			cq.add();
			vehicleWarnService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆到期查询失败", e);
			throw new BusinessException("车辆到期查询失败", e);
		}
	}

	/**
	 * 办理记录列表数据
	 * 
	 * @param vehicleWarnHis
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "hisList")
	public void hisList(VehicleWarnHis vehicleWarnHis, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(VehicleWarnHis.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicleWarnHis, request.getParameterMap());
			cq.add();
			vehicleWarnService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("办理记录查询失败", e);
			throw new BusinessException("办理记录查询失败", e);
		}
	}

	/**
	 * 增加页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		List<WarnType> warnTypeList = warnTypeService.listByStatus(WarnType.STATUS_ENABLE);
		req.setAttribute("warnTypeList", warnTypeList);
		return new ModelAndView("modules/warn/vehicleWarn-add");
	}

	/**
	 * 提醒明细tab
	 * 
	 * @return
	 */
	@RequestMapping(params = "tab")
	public ModelAndView tab(HttpServletRequest req) {
		List<WarnType> warnTypeList = warnTypeService.listByStatus(WarnType.STATUS_ENABLE);
		req.setAttribute("warnTypeList", warnTypeList);
		return new ModelAndView("modules/warn/vehicleWarn-tab");
	}

	/**
	 * 办理页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goHandle")
	public ModelAndView goHandle(VehicleWarn vehicleWarn, HttpServletRequest req) {
		if (StringUtils.isNotBlank(vehicleWarn.getId())) {
			vehicleWarn = vehicleWarnService.get(VehicleWarn.class, vehicleWarn.getId());
			req.setAttribute("vehicleWarnPage", vehicleWarn);
		}
		return new ModelAndView("modules/warn/vehicleWarn-handle");
	}

	/**
	 * 发送短信页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goSendSms")
	public ModelAndView goSendSms(VehicleWarn vehicleWarn, HttpServletRequest req) {
		if (StringUtils.isNotBlank(vehicleWarn.getId())) {
			vehicleWarn = vehicleWarnService.get(VehicleWarn.class, vehicleWarn.getId());
			req.setAttribute("vehicleWarnPage", vehicleWarn);
		}
		return new ModelAndView("modules/warn/vehicleWarn-sms");
	}

	/**
	 * 增加
	 * 
	 * @param vehicleWarn
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public Result doAdd(VehicleWarn vehicleWarn, HttpServletRequest request) {
		String msg = null;
		try {
			List<VehicleWarn> vehicleWarnList = new ArrayList<VehicleWarn>();
			String vehicleId = request.getParameter("vehicleId");
			if (StringUtils.isNotBlank(vehicleId)) {
				for (String id : vehicleId.split(",")) {
					Vehicle vehicle = new Vehicle();
					vehicle.setId(id);
					for (VehicleWarn vehicleWarnEntity : vehicleWarn.getWarnList()) {
						VehicleWarn entity = new VehicleWarn();
						entity.setVehicle(vehicle);
						entity.setWarnType(vehicleWarnEntity.getWarnType());
						entity.setWarnDate(vehicleWarnEntity.getWarnDate());
						entity.setStatus(VehicleWarn.STATUS_NORMAL);
						vehicleWarnList.add(entity);
					}
				}
			}
			vehicleWarnService.save(vehicleWarnList);
			msg = "车辆提醒增加成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			msg = "车辆提醒增加失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 办理
	 * 
	 * @param vehicleWarn
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doHandle")
	@ResponseBody
	public Result doHandle(VehicleWarn vehicleWarn, HttpServletRequest request) {
		String msg = null;
		try {
			// 办理记录
			VehicleWarnHis vehicleWarnHis = new VehicleWarnHis();
			vehicleWarnHis.setVehicle(vehicleWarn.getVehicle());
			vehicleWarnHis.setWarnType(vehicleWarn.getWarnType());
			vehicleWarnHis.setPreWarnDate(vehicleWarn.getWarnDate());
			vehicleWarnHis.setAfterWarnDate(vehicleWarn.getNextDate());
			// 提醒办理
			vehicleWarn.setStatus(VehicleWarn.STATUS_NORMAL);
			vehicleWarn.setWarnDate(vehicleWarn.getNextDate());
			vehicleWarnService.handle(vehicleWarn, vehicleWarnHis);
			msg = "车辆\"" + vehicleWarn.getVehicle().getPlateNumber() + "\"提醒办理成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "车辆\"" + vehicleWarn.getVehicle().getPlateNumber() + "\"提醒办理失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 发送短信
	 * 
	 * @param vehicleWarn
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doSendSms")
	@ResponseBody
	public Result doSendSms(VehicleWarn vehicleWarn, HttpServletRequest request) {
		String msg = null;
		String phone = request.getParameter("ownerPhone");
		try {
			Tenant tenant = tenantService.get(Tenant.class, LoginUserUtil.getLoginUser().getTenantId());
			// 判断用户余额
			if (tenant.getBalance().compareTo(Tenant.BALANCE_MIN) < 0) {
				msg = "账户余额不足,发送失败.";
				return Result.error(msg);
			}
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("plateNumber", request.getParameter("plateNumber"));
			paramMap.put("warnTypeName", request.getParameter("warnTypeName"));
			paramMap.put("warnDate", DateUtil.dateToStr(vehicleWarn.getWarnDate(), "yyyy-MM-dd"));
			String templateParam = JsonUtil.toJson(paramMap);
			smsService.sendSms(phone, SmsConfig.template_vehicle_warn, templateParam, tenant);
			msg = "号码\"" + phone + "\"短信发送成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_SMS);
		} catch (Exception e) {
			msg = "号码\"" + phone + "\"短信发送失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 启动
	 * 
	 * @return
	 */
	@RequestMapping(params = "doStart")
	@ResponseBody
	public Result doStart(VehicleWarn vehicleWarn, HttpServletRequest request) {
		String msg = null;
		try {
			vehicleWarn = vehicleWarnService.get(VehicleWarn.class, vehicleWarn.getId());
			if (vehicleWarn.getStatus().equals(VehicleWarn.STATUS_PAUSE)) {
				vehicleWarn.setStatus(VehicleWarn.STATUS_NORMAL);
				vehicleWarnService.saveOrUpdate(vehicleWarn);
			}
			msg = "车辆\"" + vehicleWarn.getVehicle().getPlateNumber() + "\"提醒启动成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "车辆\"" + vehicleWarn.getVehicle().getPlateNumber() + "\"提醒启动失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 暂停
	 * 
	 * @return
	 */
	@RequestMapping(params = "doPause")
	@ResponseBody
	public Result doPause(VehicleWarn vehicleWarn, HttpServletRequest request) {
		String msg = null;
		try {
			vehicleWarn = vehicleWarnService.get(VehicleWarn.class, vehicleWarn.getId());
			if (vehicleWarn.getStatus().equals(VehicleWarn.STATUS_NORMAL)) {
				vehicleWarn.setStatus(VehicleWarn.STATUS_PAUSE);
				vehicleWarnService.saveOrUpdate(vehicleWarn);
			}
			msg = "车辆\"" + vehicleWarn.getVehicle().getPlateNumber() + "\"提醒暂停成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "车辆\"" + vehicleWarn.getVehicle().getPlateNumber() + "\"提醒暂停失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public Result doDel(VehicleWarn vehicleWarn, HttpServletRequest request) {
		String msg = null;
		try {
			vehicleWarn = vehicleWarnService.get(VehicleWarn.class, vehicleWarn.getId());
			vehicleWarnService.delete(vehicleWarn);
			msg = "车辆\"" + vehicleWarn.getVehicle().getPlateNumber() + "\"提醒删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "车辆\"" + vehicleWarn.getVehicle().getPlateNumber() + "\"提醒删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 导出
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "xlsExport")
	public String xlsExport(VehicleWarn vehicleWarn, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid, ModelMap modelMap) {
		try {
			CriteriaQuery cq = new CriteriaQuery(VehicleWarn.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicleWarn, request.getParameterMap());
			// 提醒状态
			String status = request.getParameter("status");
			status = StringUtils.isBlank(status) ? VehicleWarn.STATUS_NORMAL : status;
			cq.eq("status", status);
			// 提醒类型
			String warnType = request.getParameter("wt");
			if (StringUtils.isNotBlank(warnType)) {
				cq.eq("warnType.id", warnType);
			}
			// 下月到期||时间范围
			String warnDateType = request.getParameter("warnDateType");
			String warnDateBegin = request.getParameter("warnDate_begin");
			String warnDateEnd = request.getParameter("warnDate_end");
			if (StringUtils.isNotBlank(warnDateBegin) || StringUtils.isNotBlank(warnDateEnd)
					|| (warnDateType != null && warnDateType.equals("2"))) {
				// 按时间范围
				if (StringUtils.isNotBlank(warnDateBegin)) {
					cq.ge("warnDate", DateUtil.strToDate(warnDateBegin, "yyyy-MM-dd"));
				}
				if (StringUtils.isNotBlank(warnDateEnd)) {
					cq.le("warnDate", DateUtil.strToDate(warnDateEnd, "yyyy-MM-dd"));
				}
			} else if ((warnDateType == null || warnDateType.equals("1"))
					&& (StringUtils.isBlank(warnDateBegin) && StringUtils.isBlank(warnDateEnd))) {
				// 下月到期
				Calendar calBegin = Calendar.getInstance();
				calBegin.add(Calendar.YEAR, -100);
				cq.ge("warnDate", calBegin.getTime());
				Calendar calEnd = Calendar.getInstance();
				calEnd.add(Calendar.MONTH, 2);
				calEnd.set(Calendar.DATE, 0);
				cq.le("warnDate", calEnd.getTime());
			}
			cq.add();
			List<VehicleWarn> vehicleList = vehicleWarnService.listByCriteria(cq);
			modelMap.put(NormalExcelConstants.FILE_NAME, "车辆到期" + "--" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
			modelMap.put(NormalExcelConstants.CLASS, VehicleWarn.class);
			modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("车辆到期", "车辆到期"));
			modelMap.put(NormalExcelConstants.DATA_LIST, vehicleList);
			return NormalExcelConstants.JEECG_EXCEL_VIEW;
		} catch (Exception e) {
			logger.error("车辆到期导出失败", e);
			throw new BusinessException("车辆到期导出失败", e);
		}
	}

}
